<template>
<div>
    <div class="e-form">
        <BillTop @cancel="printHandel"></BillTop>
        <div class="tabs warningTabs">
             <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="结算明细" name="changeDetail" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="changeHistory" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                    <div style="width: 100%" class="form">
                <el-form ref="form" :model="formData" label-width="160px" :rules="rules">
                <el-row>
                    <el-col :span="12">
                         <el-form-item label="结算编号：" >
                            {{formData.billNo}}
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                         <el-form-item label="机构：" >
                            {{formData.orgName}}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="业务类型：">
                         周材租赁合同
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="结算类型：">
                            {{setSettleType(formData.settleType)}}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="结算单位：" prop="settleOrgName">
                        <el-input
                                style="flex: 1;"
                                placeholder="选择周材租赁收入合同"
                                v-model="formData.settleOrgName"

                            >
                                <i slot="suffix" class="el-icon-document-copy" @click="settleOrgChange"></i>
                        </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="合同编号：">
                         <span>{{formData.contractNo}}</span>
                        <span class="a"
                        @click="seeSourceOrder" v-if="formData.contractNo">查看</span>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                           <el-form-item label="进退场费(元)：" prop='cost'>
                              <el-input v-model="formData.cost"
                              @change="enterExitFeeEvent"
                              type="number"
                              placeholder="请输入进退场费"
                              >
                              </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="结算日期：" v-model="formData.settleDate"
                      prop="settleDate"
                      >
                            <el-date-picker
                                v-model="formData.settleDate"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="选择日期">
                            </el-date-picker>
                    </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                         <el-form-item label="不含税金额(元)：" prop="taxExcludedAmount">
                             {{taxExcludedAmountData}}
                        </el-form-item>
                    </el-col>
                     <el-col :span="12">
                        <el-form-item label="税价合计(元)：" >
                           {{totalTaxPriceData}}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                     <el-col :span="12">
                        <el-form-item label="税率%：">
                            {{formData.taxRate || 0}}
                        </el-form-item>
                    </el-col>
                     <el-col :span="12">
                        <el-form-item label="累计结算金额：">
                          {{totalSettleAmountData}}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                         <el-form-item label="税额(元)：" prop="taxAmount">
                              <el-input v-model="formData.taxAmount"
                              @change="taxAmountEvent" type="number"
                              placeholder="请填写税额"
                              >
                              </el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                          <el-form-item label="录入人：" >
                            {{formData.inputName}}
                        </el-form-item>
                    </el-col>

                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="发票号：">
                        <el-input v-model="formData.invoiceNo"
                            placeholder="请填写发票编号"
                            v-enterInteger1
                        >
                        </el-input>
                        </el-form-item>
                    </el-col>
                     <el-col :span="12">
                        <el-form-item label="币种：" >
                            {{formData.currency}}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="本位币：" >
                            {{formData.baseCurName}}
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="税价合计(本位币)：" >
                            {{baseTotalTaxPriceData}}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                     <el-col :span="12">
                        <el-form-item label="状态：">
                           {{stateLable(formData.state)}}
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="传财务共享：">
                            {{shareLable(formData.isSharing)}}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注：">
                            <el-input placeholder="" v-model="formData.remarks" class="input-with-select" type="textarea"
                            :rows="3">
                            <span>
                                {{formData.remarks}}
                            </span>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
                        </div>
                    </div>
                     <!-- 结算明细 tps-->
                    <div id="changeDetailCon" class="con">
                        <div class="tabs-title" id="changeDetail">结算明细</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <div>
                                        <el-button size="small" class="btn-blue" @click="settleOrgChange">选择周材</el-button>
                                    </div>
                                </div>
                            </div>
                            <div class="errMessageBox">
                                <p class="errMessage" v-for="(item,index) in settlementErrorList" :key='index'>
                                    {{item}}
                                </p>
                            </div>
                           <div class="e-table">
                            <el-table
                                :data="acceptanceData"
                                border
                                ref="changeDetail"
                                style="width: 100%"
                                @cell-mouse-enter="cellMouseEnter"
                                @cell-mouse-leave="cellMouseLeave"
                                :row-class-name="tableRowClassName"
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                row-key="uuid"
                                class="table"
                                :default-expand-all='true'
                                :max-height="$store.state.tableHeight"
                                v-sortTable="{ 'tableData': acceptanceData, '_this': this, 'ref': 'changeDetail' }"
                            >
                                <el-table-column fixed label="操作" width="70">
                                    <template slot-scope="{ row,$index }">
                                        <div class="handle">
                                            <div style="cursor: pointer;"
                                            v-if='!row.children'
                                            >
                                                <img src="@/assets/btn/delete.png"  @click="handleDeletePlanList(row,$index)">
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="materialClassName"
                                    label="物资类别"
                                    fixed
                                    min-width="150"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                    fixed
                                    min-width="150"
                                >
                                </el-table-column>
                                <el-table-column prop="spec" label="规格"   min-width="150">
                                </el-table-column>
                                <el-table-column prop="texture" label="材质"  min-width="150">
                                </el-table-column>
                                <el-table-column prop="timeUnit" label="计时单位"  min-width="150">
                                </el-table-column>
                                <el-table-column
                                    label="合同数量"
                                    min-width="150"
                                    prop="contractQuantity"
                                >
                                </el-table-column>
                                 <el-table-column
                                    label="本期结算数量"
                                    min-width="150"
                                    prop="settleQuantity"
                                >
                                <template slot-scope="{row}">
                                <el-input v-model="row.settleQuantity" class="input-with-select"
                                type="number"
                                v-if='!row.children'
                                @change="settlementQuantityEvent(row.settleQuantity,row.dtlId,row.unsettledQuantity)"
                                >
                                </el-input>
                                <span v-else>{{row.settleQuantity}}</span>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    label="截止本期末累计结算数量"
                                    min-width="200"
                                    prop="currTotalQuantity">
                                    <template slot-scope="{row}" v-if="!row.children">
                                        {{currTotalQuantityData(row)}}
                                    </template>
                                </el-table-column>

                                <el-table-column
                                    label="租赁单价(元)"
                                    min-width="150"
                                    prop="price"
                                >
                                </el-table-column>

                                <el-table-column
                                    label="租赁时间"
                                    min-width="150"
                                    prop="leaseTime"
                                >
                                <template slot-scope="{row}" v-if="!row.children">
                                      {{leaseTimeData(row)}}
                                </template>
                                </el-table-column>

                                <el-table-column
                                    label="已租时间"
                                    min-width="150"
                                    prop="hasLeasedTime"
                                >
                                 <template slot-scope="{row}" v-if="!row.children">
                                      {{                              currTotalLeaseTimeData(row)}}
                                </template>
                                </el-table-column>

                                <el-table-column
                                    label="当期租金"
                                    min-width="150"
                                    prop="currAmount"
                                >
                                <template slot-scope="{row}">
                                <el-input v-model="row.currAmount" class="input-with-select"
                                type="number"
                                @change="currAmountEvent(row.currAmount,row.dtlId)"
                                v-if='!row.children'
                                >
                                </el-input>
                                </template>
                                </el-table-column>

                                <el-table-column
                                    label="截止本期末累计结算租金"
                                    min-width="200"
                                    prop="currTotalAmount"
                                >
                                <template slot-scope="{row}" v-if="!row.children">
                                      {{                              currTotalAmountData(row)}}
                                </template>
                                </el-table-column>
                            </el-table>
                        </div>
                        </div>
                    </div>
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="changeHistory">附件信息</div>
                        <AttachIndex :relationId="attachId" bucketName="facilityplan" />
                    </div>

                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                @getAuditHistory="getAuditHistory"
                                billType=6098
                                ref="AuditHistoryRef"
                                :tableData.sync="auditHistoryTable"
                            />
                        </div>
                    </div>
                </div>
            </el-tabs>
            <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
            <div class="buttons">
                <span class="tip"><span style="color: red; margin-right: 0">*</span>为必填项</span>
                 <PccExaButtons :state="deleteBut" :auditState="auditState" @exas="exas" :founderId="formData.founderId"/>
                  <el-button
                    type="primary"
                    class="btn-blue"
                    @click="printHandel"
                    size="small"
                    v-debounce
                    >关闭</el-button
                >
            </div>
         </div>
    </div>
</div>

</template>

<script>
import { mapState, mapMutations } from 'vuex'
import request from '@/api/PCCset/apply.js'
import '@/utils/jquery.scrollTo.min'
import AttachIndex from '@/components/common/attachIndex'
import ComAuditHistoryIndex from '@/pages/equipment/components/auditHistory/auditHistoryIndex'
import { hideLoading, selectDataClient, throttle, getUuid, openAppClient } from '@/utils/common'
import PccExaButtons from '@/components/common/exaButtons.vue'
import httpRequest from '@/api/settlementManagement/weeklyMaterialSettlement/rentalTradeIncome'
import publicRequest from '@/api/settlementManagement/publicRequest/publicRequest'

export default {
    data () {
        return {
            deleteBut: 0,
            isShowPrint: true,
            billId: this.$route.query.billid,
            fake: true,    //判断changeType的数值  -1 1 2
            auditHistoryTable: [], //审核历史表格
            SetFinalSettle: false,
            errorAcceptanceMsg: [], // 结算明细
            visibleNewPlan: false,  //结算单位页面
            visibleKou: false,
            visibleReturn: false,
            tabsName: 'baseInfo',
            checkedBox: false,
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            tableData: [],
            isRedSingle: false,
            formData: {
                //配置计划基础信息
                baseCurId: '', //本位币ID
                baseCurName: '', //本位币名称
                baseTaxRate: '', //本位币汇率
                billId: '', //单据ID
                billNo: '', //单据编号
                currency: '', //币种
                currencyId: '', //币种ID
                isRed: 0, //是否红单
                isSharing: 0, //是否传财务共享
                nullifyCreated: '', //作废时间
                nullifyCreator: '', //作废人名称
                nullifyCreatorId: '', //作废人ID
                nullifyDescription: '', //作废描述
                nullifyReason: '', //作废原因
                operatorId: '', //经办人ID
                operatorName: '', //经办人名称
                orgId: '', //机构ID
                orgName: '', //机构名称
                parentId: '', //父级ID
                remarks: '', //备注
                settleAmount: 0, //结算金额
                settleDate: '', //结算日期 'settleDate': formatDate(new Date(), 'yyyy-MM-dd'),
                settleOrgId: '', //结算单位ID
                settleOrgName: '', //结算单位名称
                sourceId: '', //源单ID
                sourceNo: '', //源单编号
                state: 0, //状态
                taxAmount: 0, //税额
                taxRate: 0, //税率
                totalSettleAmount: 0, //累计结算金额
                workId: '', //流程id
                contractAmount: 0, //合同金额
            },
            //结算明细
            acceptanceData: [
                {
                    'children': [
                    ],
                    'topClassId': '',
                    'topClassName': '',
                    'totalAmount': 0,
                    'totalQuantity': 0,
                    'uuid': '45878szxzxsdsdwd'
                }
            ],
            //需要删除的结算明细数据
            deleteDataList: [],
            changeHistoryTable: [], //变更历史表格
            changeHistorySelect: [], //变更历史选择项
            //基本信息验证数据
            rules: {
                settleOrgName: [
                    { required: true, message: '请选择调动单', trigger: 'blur' }
                ],
                cost: [
                    { required: true, message: '请填写进退场费', trigger: 'blur' }
                ],
                taxAmount: [
                    { required: true, message: '税额不能为空', trigger: 'blur' }
                ],
                settleDate: [
                    { required: true, message: '请选择结算日期', trigger: 'change' }
                ],
                remarks: [
                    { max: 500, message: '长度不超过500个字符', trigger: 'blur' }
                ],
            },
            checkPerson: false,
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [], //计划明细错误显示
            isErrorMsg: true, //是否提醒错误信息
            auditState: {}, //流程按钮显示状态
            //提交审核参数
            auditParams: {
                'billId': this.$route.query.billid,
                'billType': 6098,
                'freeNextUnitIndex': 0,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': ''
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 6098,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
            winEvent: {},
            //获取当前页面可以操作的按钮
            buttonParams: {
                'billId': this.$route.query.billid,
                'billType': 6098, // 对应模块Id
                'freeNextUnitIndex': 0,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': ''
            },
            //结算明细中用于提示错误的数据
            settlementErrorList: []
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
        }),
        //根据状态值参数决定是否展示打印按钮
        stateLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state
                const obj = state.find(x=>x.value === param)
                return (obj ?  obj.label :  '')
            }
        },
        //传输财务共享
        shareLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.shareFrom
                const obj = state.find(x=>x.value === param)
                return (obj ?  obj.label :  '')
            }
        },
        attachId () {
            return this.$route.query.billid
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 258 - this.lastConHeight
        },
        //不含税金额
        taxExcludedAmountData () {
            let total = 0
            this.acceptanceData[0].children.forEach(item=>{
                total += Number(item.currAmount)
            })
            return total + Number(this.formData.cost)
        },
        //税价合计
        totalTaxPriceData () {
            return this.taxExcludedAmountData + Number(this.formData.taxAmount)
        },
        //税价合计（本位币）
        baseTotalTaxPriceData () {
            return this.totalTaxPriceData * this.formData.baseTaxRate
        },
        //累计结算金额
        totalSettleAmountData () {
            let val = 0
            this.acceptanceData[0].children.forEach(item=>{
                val += Number(item.currTotalAmount || 0)
            })
            return val
        },
        //-----明细----//
        //租赁时间
        leaseTimeData () {
            return row=>{
                let val = 0
                if(row.currAmount && row.settleQuantity && row.price) {
                    val = (Number(row.currAmount) / (row.settleQuantity * row.price)).toFixed(2) * 1
                }
                this.setDataRetainTwoDecimal(this.acceptanceData[0].children, row.dtlId, 'leaseTime', val)
                return val
            }
        },
        //截止本期末累计结算数量
        currTotalQuantityData () {
            return row=>{
                let val = 0
                val = Number(row.settleQuantity || 0) + Number(row.prevTotalQuantity || 0)
                this.setDataRetainTwoDecimal(this.acceptanceData[0].children, row.dtlId, 'currTotalQuantity', val)
                return val
            }
        },
        //截止本期末累计结算时间
        currTotalLeaseTimeData () {
            return row=>{
                let val = 0
                val = Number(row.leaseTime || 0) + Number(row.prevTotalTime || 0)
                this.setDataRetainTwoDecimal(this.acceptanceData[0].children, row.dtlId, 'hasLeasedTime', val)
                return val
            }
        },
        //截止本期末累计结算金额
        currTotalAmountData () {
            return row=>{
                let val = 0
                val = Number(row.currAmount || 0) + Number(row.prevTotalAmount || 0)
                this.setDataRetainTwoDecimal(this.acceptanceData[0].children, row.dtlId, 'currTotalAmount', val)
                return val
            }
        }

    },
    components: {
        AttachIndex,
        ComAuditHistoryIndex,
        PccExaButtons
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    created () {
        this.formData.inputName = localStorage.getItem('userName')
        this.billid = this.$route.query.billid
        this.userId = localStorage.getItem('userId')
        this.formData.orgId = this.userInfo.orgInfo.orgId
    },
    mounted () {
        this.init()
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()
        // 保存所有tabName
        const arr = ['baseInfo', 'changeDetail', 'changeHistory', 'auditHistory']
        this.tabArr = arr
        let $idsTop = []
        const onScroll = () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        }
        this.winEvent.onScroll = onScroll
        window.addEventListener('scroll', this.winEvent.onScroll)
        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        const onResize = () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        }
        this.winEvent.onResize = throttle(onResize, 500)
        window.addEventListener('resize', this.winEvent.onResize)
        this.scorllDtl()
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.winEvent.onScroll)
        window.removeEventListener('resize', this.winEvent.onResize)
    },
    //tps
    methods: {
        ...mapMutations(['setSelectedInfo', 'setAuditParams']),
        //重新赋值并保留两位小数
        setDataRetainTwoDecimal (list, dtlId, key, val, decimal = 2) {
            const length = list.length
            for (let i = 0; i < length; i++) {
                if(list[i].dtlId == dtlId) {
                    list[i][key] = Number(val).toFixed(decimal) * 1
                    break
                }
            }
        },
        //当期租金事件
        currAmountEvent (val, dtlId) {
            this.setDataRetainTwoDecimal(this.acceptanceData[0].children, dtlId, 'currAmount', val)
            this.formData.taxAmount = this.computedTaxAmount()
        },
        //计算合同总金额
        totalContractAmount () {
            let total = 0
            this.acceptanceData[0].children.forEach(item=>{
                total += Number(item.contractAmount || 0)
            })
            return total
        },
        //计算总税额
        computedTaxAmount () {
            let total = 0
            this.acceptanceData[0].children.forEach(item=>{
                total += Number(item.currAmount) * (this.formData.taxRate / 100)
            })
            return total.toFixed(2) * 1
        },
        //进退场费事件
        enterExitFeeEvent (val) {
            if(val < 0) {
                this.$message.error('进退场费不能小于0')
                this.formData.cost = 0
            } else if(val > 0) {
                this.formData.cost = Number(val).toFixed(2) * 1
            } else {
                this.formData.cost = 0
            }
        },
        //结算明细-结算数量验证
        settlementQuantityEvent (val, dtlId, unsettledQuantity) {
            //不可大于未结算数量
            if(val > unsettledQuantity) {
                this.$message.error(`结算数量不可大于未结算数量,当前未结算数量为${unsettledQuantity}`)
            }
            val = val <= unsettledQuantity ? val : unsettledQuantity
            this.setDataRetainTwoDecimal(this.acceptanceData[0].children, dtlId, 'settleQuantity', val)
        },
        //总税额验证
        taxAmountEvent (val) {
            this.formData.taxAmount = val && val > 0 ? ((val * 1).toFixed(2) * 1 ) : 0
        },
        //计算截至本期末累计结算金额
        computedCurrentSettleAmount (currAmount, prevTotalSettleAmount = 0) {
            return (currAmount * 1 + prevTotalSettleAmount * 1).toFixed(2) * 1
        },
        //处理结算明细数据
        setDetailsData (list) {
            list.forEach(item=>{
                item.materialClassName = item.topClassName
                item.uuid = getUuid()
                item.children && item.children.forEach(v=>{
                    v.uuid = getUuid()
                    v.parentId = item.uuid
                    v.children && v.children.forEach(t=>{
                        v.uuid = getUuid()
                        v.parentId = t.uuid
                    })
                })
            })
        },
        //合并结算明细数据
        mergeDetailsData (list) {
            this.acceptanceData[0].children.forEach(item=>{
                list.forEach(l=>{
                    if(item.sourceDtlId == l.sourceDtlId) {
                        item.prevTotalAmount = l.prevTotalAmount || 0 //截止上期末累计结算金额
                        item.prevTotalQuantity = l.prevTotalQuantity || 0 //截止上期末累计结算数量
                        item.prevTotalTime = l.prevTotalTime || 0 //截止上期末累计结算时间
                    }
                })
            })
        },
        //删除结算明细
        acceptanceDelete (row) {
            row.changeType = -1
        },
        // 如果changeType是删除,则隐藏这一行
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        // elment表格事件
        cellMouseEnter (row) {
            this.MouseEnterId = row.billId
        },
        // elment表格事件
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        //刷新历史审核列表
        getAuditHistory () {
            publicRequest.adoptIdObtainGetAuditHistory(this.auditParams).then(res=>{
                this.auditHistoryTable = res
            })
        },
        //初始化数据
        init () {
            Promise.all([
                this.getInfo(),
                this.getAuditHistory(),
            ]).finally(() => {
                hideLoading()
            })
        },
        //获取基本信息数据编辑页面
        getInfo () {
            //接口通用参数
            const params = {
                id: this.billid,
            }
            // 获取基本信息 tps
            httpRequest.searchRentalTradeIncomeData(params).then(res=>{
                //获取当前页面可以操作的按钮
                publicRequest.adoptIdObtainGetButtonsData(this.buttonParams).then(butRes=>{
                    if(res.state == 1) {
                        butRes.canAudit = false // 被打回的审核状态不存在审核和作废功能
                        butRes.canUndoAudit = false // 测回同理
                        this.deleteBut = 1 // 删除同理
                        this.isShowPrint = false // 打印同理
                    }
                    this.auditState = butRes
                })
                this.formData = { ...res }
            })
            //获取结算明细
            httpRequest.searchRentalTradeIncomeDetailedcData({ billId: this.billid }).then(res=>{
                if(res.length > 0) {
                    this.setDetailsData(res)
                    this.acceptanceData = res
                    // httpRequest.getRentalTradeIncomeDetailedTimeAndAmountAndNumberData(this.acceptanceData[0].children).then(res=>{
                    //     this.mergeDetailsData(res)
                    // })
                }
            })
        },
        //弹窗选择结算明细
        settleOrgChange () {
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: '/subcontract/thirdParty/getLeaseIncomeSettlement', //调动单和物资弹框
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: '',
                Title: '选择周材租赁收入合同' // 标题
            }).then(val => {
                this.setSettlementDetailsData(val)
                if(this.acceptanceData[0].children.length > 0) {
                    httpRequest.getRentalTradeIncomeDetailedTimeAndAmountAndNumberData(this.acceptanceData[0].children).then(res=>{
                        this.mergeDetailsData(res)
                    })
                }
            })
        },
        //更新结算明细数据
        setSettlementDetailsData (val) {
            if(val.length > 0 && val) {
                const obj = {}
                //判断弹框选择的物资是否已在数组children中
                const childern = this.acceptanceData[0].children
                const dataLength = childern.length
                const valLength = val.length
                const targetList = []
                const fatherList = [] //父级id用于给子级加结算单位字段
                for (let i = 0; i < valLength; i++) {
                    let isRepeat = false
                    //跳过父级
                    if(val[i].parentId == '0') {
                        fatherList.push({ fatherId: val[i].billId, fatherSettlementUnit: val[i].firstPartyName//结算单位
                        })
                        continue
                    }
                    for (let j = 0; j < dataLength; j++) {
                        //如果有则直接跳过
                        if(childern[j].sourceDtlId == val[i].billId) {
                            isRepeat = true
                            break
                        }
                    }
                    //没有就新增
                    if(!isRepeat) {
                        const target = val[i]
                        target.uuid = getUuid() //表格需要的id
                        target.sourceDtlId = target.billId || '' //源单Id
                        target.billId = this.billId // 传给后端需要把billId改为对应单据的billId
                        target.spec = target.specificationModel // 规格
                        target.texture = target.textureOfMaterial // 材质
                        target.timeUnit = target.unit // 计时单位
                        target.currAmount = target.currAmount || 0  //当期租金
                        target.contractId = target.contractId || '' // 合同id
                        target.contractQuantity = target.contractQuantity || 0 //合同数量
                        target.price = target.unitPrice || 0 // 单价
                        target.materialClassId = target.typeId //物资类别id
                        target.materialClassName = target.typeName // 物资类别名称
                        target.settleQuantity = target.unsettledQuantity || 0 //本期结算数量=未结算数量
                        target.unsettledQuantity = target.unsettledQuantity || 0 //未结算数量
                        target.contractAmount = target.amount || 0, // 合同金额
                        target.changeType = 1 //新增
                        targetList.push(target)
                        const length = fatherList.length
                        for (let i = 0; i < length; i++) {
                            if(fatherList[i].fatherId == target.parentId) {
                                obj.settleOrgName = fatherList[i].fatherSettlementUnit || '' //结算单位
                                break
                            }
                        }
                        obj.settleOrgName = obj.settleOrgName || target.firstPartyName  //结算单位-没有父级时取子级的字段
                        obj.baseCurId = target.baseCurId || '', //本位币id
                        obj.baseCurName = target.baseCurName || '', //本位币名称
                        obj.baseTaxRate = target.baseCurRate || 1, //本位币汇率
                        obj.currencyId = target.currencyId || '', //币种id
                        obj.currency = target.currencyName || '', //币种
                        obj.taxRate = target.taxRate || 0, // 税率
                        obj.contractId = target.contractId || '' // 合同id
                        obj.contractNo = target.contractNumber || '' //合同编号
                    }
                }
                this.acceptanceData[0].children.push(...targetList)
                this.formData = { ...this.formData, ...obj }
            }
        },
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //删除单条结算明细数据
        handleDeletePlanList (row) {
            let isSwitch = true
            this.acceptanceData.forEach(item=>{
                item.children.forEach((s, i)=>{
                    if(s.dtlId == row.dtlId) {
                        this.clientPop(
                            'info',
                            this.oneDeleteErr,
                            ()=>{
                                //判断此条数据是否为新增
                                if(s.changeType != 1) {
                                    const target = {
                                        dtlId: s.dtlId,
                                        changeType: -1
                                    }
                                    this.deleteDataList.push(target)
                                }
                                item.children.splice(i, 1)
                                //更新页面
                                this.taxAmountEvent(this.formData.taxAmount)
                            }
                        )
                        //找到目标后没有必要继续循环直接退出
                        isSwitch = false
                        return
                    }
                })
                if(!isSwitch) {
                    return
                }
            })
        },
        //删除草稿状态的变更历史
        handleChangeHistory () {
            const length = this.changeHistorySelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.changeHistorySelect.forEach(item=>{
                    if(item.state !== 0) {
                        this.clientPop(
                            'info',
                            '只有草稿状态才可以删除！',
                        )
                        this.$refs.changeHistorySelect.clearSelection()
                    }else{
                        this.clientPop(
                            'info',
                            `已选择【${length}】条数据，确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。`,
                            this.deleteChangeHistory
                        )
                    }
                })
            }
        },
        //批量或单独删除变更历史
        deleteChangeHistory () {
            let billids = []
            this.changeHistorySelect.forEach(item=>{
                if(item.state === 0) {
                    billids.push(item.billId)
                    request.leaseDelete(billids).then(()=>{
                        this.init()
                        this.clientPop('suc', '删除成功')
                        this.$refs.changeHistorySelect.clearSelection()
                    })
                }
            })
        },
        //处理明细参数并返回保存参数
        setParams () {
            //处理明细参数
            this.acceptanceData[0].children.forEach(item=>{
                if(item.changeType == 1) {
                    item.dtlId = '' // 传给后端时需要把此id清空用于后端重新添加唯一id号
                }else {
                    item.changeType = 2
                }
            })
            if(this.deleteDataList.length > 0) {
                this.acceptanceData[0].children.push(...this.deleteDataList)
            }
            //处理基本信息中用计算属性计算的参数
            const obj = {
                totalTaxPrice: this.totalTaxPriceData,
                baseTotalTaxPrice: this.baseTotalTaxPriceData,
                taxExcludedAmount: this.taxExcludedAmountData,
                totalSettleAmount: this.totalSettleAmountData,
                contractAmount: this.totalContractAmount ()
            }
            const paramsList = [httpRequest.storageRentalTradeIncomeBasicData({
                ...this.formData,
                ...obj,
                taxRate: parseInt(this.formData.taxRate)
            }), httpRequest.storageRentalTradeIncomeDetailedcData(this.acceptanceData),
            ]
            this.setSelectedInfo(paramsList)
            return paramsList
        },
        //验证基本信息
        verificationEssentialInformation () {
            const { settleOrgName, taxRate, taxAmount, settleDate, cost } = this.formData
            const list = [settleOrgName, taxRate, taxAmount, settleDate, cost]
            return list.some(item=>String(item) == '' || item == null)
        },
        //验证结算明细
        verificationSettlementDetails () {
            const errListAll = []
            this.acceptanceData[0].children.forEach((item, index)=>{
                const errList = []
                if(item.settleQuantity == 0 || item.settleQuantity == '') {
                    errList.push(`结算数量不能为空或0且不能超过未结算数量：${item.unsettledQuantity}`)
                }
                if(errList.length > 0) {
                    const err = `第${index + 1}行中：${errList.join('、')}`
                    errListAll.push(err)
                }
            })
            return errListAll
        },
        //验证数据是否符合要求
        requirementsVerification () {
            return this.totalTaxPriceData <= this.totalContractAmount()
        },
        //保存全部数据
        saveAll () {
            const paramsList = this.setParams ()
            Promise.all(paramsList)
                .then(()=>{
                    this.clientPop('suc', '数据保存成功')
                    location.reload()
                })
                .catch(()=>{
                    this.clientPop('err', '数据保存失败', ()=>{
                        this.scorllError()
                    })
                })
                .finally(() => {
                    hideLoading()
                })
        },
        //保存并提交
        submitCommit () {
            this.errorList = []
            //验证基本信息
            if(this.verificationEssentialInformation()) {
                this.setError('baseInfo')
                this.scorllError()
                // this.clientPop('err', '请完善基本信息')
                this.$message.error('请完善基本信息')
                return
            }
            //验证税价合计是否超合同金额
            if(!this.requirementsVerification()) {
                this.setError('baseInfo')
                this.scorllError()
                this.clientPop('err', `税价合计${this.totalTaxPriceData}，已超合同金额${this.totalContractAmount ()}，请修改后再提交！`)
                return
            }
            //验证是否存在明细
            if(this.acceptanceData[0].children.length === 0) {
                this.settlementErrorList = ['结算明细不能为空！']
                this.setError('changeDetail')
                this.scorllError()
                return
            }
            //验证结算明细
            const errSettlementDetailsList = this.verificationSettlementDetails()
            if(errSettlementDetailsList.length > 0) {
                this.settlementErrorList = errSettlementDetailsList
                this.setError('changeDetail')
                this.scorllError()
                return
            }
            const paramsList = this.setParams ()
            Promise.all(paramsList)
                .then(()=>{
                    publicRequest.adoptIdObtainSubmitForReview(this.auditParams)
                        .then(()=>{
                            this.clientPop('suc', '保存并提交成功', ()=>{
                                this.printHandel()
                            })
                        })
                        .catch(()=> {
                            this.clientPop('err', '提交失败！')
                        })
                })
                .catch(()=>{
                    this.clientPop('err', '保存失败', ()=>{
                        this.scorllError()
                    })
                })
        },
        /*审核相关操作*/
        //删除
        deleteData () {
            this.clientPop(
                'info',
                '确定要删除吗？数据删除后不可恢复，请谨慎操作！',
                ()=>{
                    httpRequest.deleteRentalTradeIncomeData({ id: this.attachId }
                    ).then(res=>{
                        if(res.code == 200) {
                            this.clientPop('suc', '删除成功', ()=>{
                                this.printHandel()
                            })
                        }
                    })
                }
            )
        },
        //按钮事件
        exas (arg) {
            if (arg === 'submitCommit') {
                this.submitCommit()  //保存并提交
            } else if (arg === 'submit') {
                this.saveAll()   //保存
            } else if (arg === 'deleteData') {
                this.deleteData() //删除
            }
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                const lastCon = document.getElementById('auditHistoryCon')
                if (lastCon) {
                    const lastConHeight = lastCon.offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        //操作成功后返回列表页面
        printHandel () {
            this.$router.replace('/rentalTradeIncomeList')
        },
        //查看源单页面
        seeSourceOrder () {
            openAppClient(`/ctleaseIncomeApplyShow?billid=${this.formData.contractId}&isview=true`, '周材租赁收入合同详情')
        },
        //当前结算类型
        setSettleType (settleType) {
            const obj = {
                1: '内部列账',
                2: '外来发票',
            }
            return obj[settleType] || ''
        },
    }
}

</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;
}
.handle {
    margin-top: 10px;
}
.errMessage {
    color: red;
    font-size: 14px;
}
</style>
